<?php

declare(strict_types=1);

namespace App\Cola\Amqp\Consumer;

use App\Cola\Service\ColaBillService;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Hyperf\Di\Annotation\Inject;
use PhpAmqpLib\Message\AMQPMessage;

#[Consumer(exchange: 'bill_submit_exchange', routingKey: 'bill_submit_routing_key', queue: 'bill_submit_queue', name: "BillSubmitConsumer", nums: 1)]
class BillSubmitConsumer extends ConsumerMessage
{
    #[Inject]
    protected ColaBillService $billService;

    /**
     * 消费者启用状态
     *
     * @return bool
     */
    public function isEnable(): bool
    {
        return true;
    }

    /**
     * 处理消费消息
     *
     * @param mixed $data 消息数据
     * @param AMQPMessage $message RabbitMQ 消息对象
     * @return Result 消费结果
     */
    public function consumeMessage($data, AMQPMessage $message): Result
    {
        try {
            $this->billService->addService($data);
            return Result::ACK;
        } catch (\Exception $e) {
            logger()->error('[账单同步]失败: ' . $e->getMessage(), [
                'data' => $data,
                'exception' => $e,
            ]);
            return $this->handleConsumeException($e);
        }
    }

    /**
     * 获取消息类型
     *
     * @return Type 消息类型
     */
    public function getType(): Type
    {
        return Type::DIRECT;
    }

    /**
     * 处理消费异常
     *
     * @param \Exception $e 异常对象
     * @return Result 消费结果
     */
    protected function handleConsumeException(\Exception $e): Result
    {
        // 根据异常类型或其他条件选择返回结果
        if ($e instanceof SomeSpecificException) {
            // 特定异常情况下，选择重试或其他处理方式
            return Result::NACK; // 重新放回队列
        }
        return Result::DROP; // 不重新放回队列
    }
}
